package com.chushouya.product.dao.repository;

import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Longs;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import com.chushouya.product.dao.entity.CategoryBrandEntity;
import com.chushouya.product.dao.mapper.CategoryBrandEntityMapper;
import com.chushouya.product.dto.admin.category.CategoryBrandQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;


@Repository
@Slf4j
public class CategoryBrandRepository extends BaseRepository<CategoryBrandEntityMapper, CategoryBrandEntity, Long> {


    private Example buildExample(CategoryBrandQuery query) {
        final Example example = this.buildExample();
        if (Longs.notNullAndZero(query.getCategoryId())) {
            example.and().andEqualTo("categoryId", query.getCategoryId());
        }
        if (Lists.isNotEmpty(query.getCategoryIdList())) {
            example.and().andIn("categoryId", query.getCategoryIdList());
        }
        if (Objects.nonNull(query.getBrandId())) {
            example.and().andEqualTo("brandId", query.getBrandId());
        }
        if (Lists.isNotEmpty(query.getBrandIdList())) {
            example.and().andIn("brandId", query.getBrandIdList());
        }
        example.orderBy("sort").asc();
        return example;
    }

    public CategoryBrandEntity selectOne(CategoryBrandQuery query) {
        return this.selectFirstOneByExample(this.buildExample(query));
    }

    public List<CategoryBrandEntity> selectList(CategoryBrandQuery query) {
        return this.selectByExample(this.buildExample(query));
    }

    public PageResult<CategoryBrandEntity> selectPage(CategoryBrandQuery query) {
        return this.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public Integer selectCount(CategoryBrandQuery query) {
        return this.selectCountByExample(this.buildExample(query));
    }

    public Integer getMaxSort(Long categoryId) {
        return 0;
//        return this.mapper.getMaxSort(categoryId);
    }
    
    /**
     * 根据分类ID查询品牌关系列表
     */
    public List<CategoryBrandEntity> selectByCategoryId(Long categoryId) {
        CategoryBrandQuery query = new CategoryBrandQuery();
        query.setCategoryId(categoryId);
        return this.selectList(query);
    }
}